#include "olineui.h"
#include "ui_olineui.h"
#include <QDebug>
#include "tcpclient.h"
#include <QMessageBox>

OlineUI::OlineUI(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::OlineUI)
{
    ui->setupUi(this);
}

OlineUI::~OlineUI()
{
    delete ui;
}

void OlineUI::show_user(PDU *pdu)
{
    if (!pdu) return;

    ui->listWidget->clear();
    QStringList names;
    uint msg_len = pdu->uiMsgLen;
    int size_ = msg_len / 32;
    char* ch;
    for (int i = 0; i < size_; i++) {
        ch = (char*)(pdu->caMsg)+i*32;
        // ui->listWidget->addItem(QString(QLatin1String(ch)));
        ui->listWidget->addItem(ch);
    }
}

void OlineUI::on_pushButton_clicked()
{
    QListWidgetItem * item = ui->listWidget->currentItem();
    if (item) {
        QString user_name = item->text();
        QString my_name = TcpClient::getInstance().get_login_name();
        if (user_name == my_name) return;  //自己不用添加自己
        // qDebug() << user_name << " -" << my_name;

        PDU* pdu = makePDU(0); //注册的实际消息长度=0
        pdu->uiMsgType = ENUM_MSG_TYPE_ADD_FRIEND_REQUEST;
        strncpy(pdu->caData, user_name.toStdString().c_str(), user_name.size());
        strncpy(pdu->caData+32, my_name.toStdString().c_str(), my_name.size());

        TcpClient::getInstance().getTcpSocket().write((char*)pdu, pdu->uiPDULen); //socket 发送
        // pdu->printPDU();
        free(pdu);
        pdu = NULL;
    } else {
        QMessageBox::critical(NULL, "没有选择用户", "请选择在线用户");
    }
}

